<template>
    <!-- 按钮 -->
    <el-button :disabled="!category3Id" type="primary" icon="ele-CirclePlusFilled" @click="emit('setState' , 1)">添加SPU</el-button>

    <!-- SPU分页列表 -->
    <el-table :data="tableData" border stripe :style="{ marginTop: '40px', marginBottom: '40px' }">
        <el-table-column type="index" width="100" label="序号" align="center" />
        <el-table-column label="SPU名称" prop="spuName" />
        <el-table-column label="SPU描述" prop="description" />
        <el-table-column label="操作">
            <template #="{ row }">
                <el-button type="primary" icon="ele-Plus" @click="emit('setState' , 2 , row)" title="添加sku"></el-button>
                <el-button type="primary" icon="ele-Edit" @click="emit('setState' , 1 , row)" title="修改spu"></el-button>
                <el-button type="info" icon="ele-Warning" @click="" title="查看sku"></el-button>
                <el-button type="danger" icon="ele-Delete" @click="" title="删除spu"></el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 页码 -->
    <el-pagination v-model:current-page="page" v-model:page-size="limit" :pager-count="7" :total="total"
        :page-sizes="[3, 5, 7, 10]" layout="prev, pager, next , sizes, total"></el-pagination>

</template>

<script lang="ts">
import { defineComponent } from "vue";
import { ElMessage } from "element-plus";

export default defineComponent({
    name: "SpuList",
});
</script>

<script setup lang="ts">
import { requestSpuList, type SpuInfoType } from "@/api/spu";
import { watch, ref } from "vue"
import useAttrStore from "@/stores/category";
import { storeToRefs } from "pinia";

//接收自定义事件
const emit = defineEmits<{
    (event: "setState" , state: number , row?: SpuInfoType):void
}>()

//1.定义表格和页码数据
const tableData = ref<SpuInfoType[]>([])
const page = ref(1)
const limit = ref(6)
const total = ref(0)

//2.拿到pinia中的数据
const attrStore = useAttrStore()
const { category3Id } = storeToRefs(attrStore)

//封装函数请求spu分页列表
const getSpuPageList = async () => {
    try {
        //发送分页列表请求
        const result = await requestSpuList(page.value, limit.value, category3Id.value as number)
        //把分页列表数据保存
        tableData.value = result.records
        //保存总页数数据
        total.value = result.total
    } catch (error) {
        //失败提示
        ElMessage.error("请求分页列表失败!")
    }
}
//3.监听category3Id请求分页列表
watch(category3Id, () => {
    //当3Id为null的时候，不发送请求，并清空分页列表数据和总页数
    if (category3Id.value === null) {
        tableData.value = []
        total.value = 0
        return;
    }
    //发送分页列表请求
    getSpuPageList()
}, { immediate: true })

//4.监听页码改变发送请求
watch([page, limit], () => {
    //3Id为null的之后,数据清空不发送请求 ， page有可能改为1，就会发送请求，则我们阻止发送请求
    if (category3Id.value === null) return
    getSpuPageList()
})

</script>